package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Wrapper;
import java.util.List;

@Service
public class ApArticleServiceImpl implements ApArticleService {
    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleConfigMapper configMapper;

    @Autowired
    private ApArticleContentMapper contentMapper;

    @Override
    public ResponseResult loadArticleList(ArticleHomeDto dto, byte type) {
        List<ApArticle> list = apArticleMapper.loadArticleList(dto, type);
        return ResponseResult.okResult(list);
    }

    /**
     * 保存或更新文章数据
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveOrUpdate(ArticleDto dto) {
        //1.检查数据是否为空
        if (null == dto) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.拷贝数据到pojo
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);

        //3.判断传递过来的数据中是否包含了id，如果包含则更新，如果没有则新增
        if (null == apArticle.getId()) {
            //3.1保存文章数据
            apArticleMapper.insert(apArticle);
            //保存文章配置
            ApArticleConfig config = new ApArticleConfig(apArticle.getId());
            configMapper.insert(config);
            //保存文章内容
            ApArticleContent content = new ApArticleContent();
            content.setArticleId(apArticle.getId());
            content.setContent(dto.getContent());
            contentMapper.insert(content);

        } else {

            //3.2更新文章数据
            apArticleMapper.updateById(apArticle);
            //修改文章内容
            ApArticleContent articleContent = contentMapper.selectOne(Wrappers.
                    <ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId,
                            apArticle.getId()));
            articleContent.setContent(dto.getContent());

            contentMapper.updateById(articleContent);
        }


        //4.封装返回结果
        return ResponseResult.okResult(apArticle.getId());
    }
}
